<template>
  <BasicModal
    v-bind="$attrs"
    :title="isUpdate ? t('common.edit') : t('common.create')"
    @register="register"
    @ok="handleSubmit"
    :destroyOnClose="true"
    :minHeight="100"
    :width="400"
  >
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { getcodeDefinedForm } from './data';

  import { useMessage } from '/@/hooks/web/useMessage';

  const isUpdate = ref<boolean>(false);
  const dataIndex = ref<number>(0);
  const { t } = useI18n();
  const { createMessage } = useMessage();
  const emit = defineEmits(['register', 'updateTable', 'addTable']);

  // 提交
  const handleSubmit = async () => {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      if (unref(isUpdate)) {
        values.index = dataIndex.value;
        emit('updateTable', values);
      } else {
        emit('addTable', values);
      }
      closeModal();
    } finally {
      setModalProps({ confirmLoading: false });
    }
  };

  // 初始化弹窗
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      dataIndex.value = data.record.index;
      setFieldsValue(data.record);
    }
  });

  // 属性详情
  const [registerForm, { validate, setFieldsValue, resetFields }] = useForm({
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
    schemas: getcodeDefinedForm(),
    showResetButton: false,
    showSubmitButton: false,
  });
</script>
